package com.luhuiguo.sso.web.components;

import java.security.Principal;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.ValidationDecorator;
import org.apache.tapestry5.annotations.AfterRender;
import org.apache.tapestry5.annotations.BeginRender;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.internal.services.ComponentInvocationImpl;
import org.apache.tapestry5.internal.services.LinkImpl;
import org.apache.tapestry5.internal.services.OpaqueConstantTarget;
import org.apache.tapestry5.internal.services.RequestPathOptimizer;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Environment;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.RequestGlobals;
import org.apache.tapestry5.services.Response;

import com.luhuiguo.tapestry.CustomValidationDecorator;

public class Layout {

	@Inject
	private Environment environment;

	@Inject
	private Request request;

	@Inject
	private Response response;

	@Inject
	private RequestPathOptimizer requestPathOptimizer;

	@Inject
	private RequestGlobals requestGlobals;

	@Parameter(required = true)
	private String title;

	@BeginRender
	public void beginRender(MarkupWriter writer) {
		environment.push(ValidationDecorator.class,
				new CustomValidationDecorator(environment, writer));
	}

	@AfterRender
	public void afterRender(MarkupWriter writer) {
		environment.pop(ValidationDecorator.class);
	}

	@OnEvent(value = EventConstants.ACTION, component = "logout")
	Object logout() {
		return new LinkImpl(response, requestPathOptimizer, null, request
				.getContextPath(), new ComponentInvocationImpl(
				new OpaqueConstantTarget("j_spring_security_logout"),
				new String[0], null), false);
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getTitle() {
		return title;
	}
	
	
	public String getUsername() {
		Principal principal = requestGlobals.getHTTPServletRequest()
				.getUserPrincipal();
		return principal == null ? "" : principal.getName();
	}

	public boolean isLoggedIn() {
		return getUsername() != null && getUsername() != "";

	}

	public boolean isAdmin() {
		return requestGlobals.getHTTPServletRequest()
				.isUserInRole("ROLE_ADMIN");
	}

}
